package common.util;

import com.han.http.client.exception.NullContentMatchedException;
import com.han.http.util.Regex;
import common.entity.LeaderEntity;
import common.entity.LeaderNewsEntity;
import common.sql.Operator;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import static com.han.http.util.Print.printlnInfo;

/**
 * @author: Han
 * @date: 2018/9/17 10:13
 * @dscription: 文本内容工具
 */
public class ContentUtil {

    private final static Operator OPERATOR;
    private final static List<LeaderEntity> LEADER_ENTITY_LIST;

    static {
        OPERATOR = Operator.getInstance();
        LEADER_ENTITY_LIST = OPERATOR.queryLeaderList();
    }

    /**
     * 清洗文章链接
     *
     * @param href 待清洗链接
     * @param url  原始链接
     * @return 清洗后的链接
     */
    public static String washArticleUrl(String href, String url) {
        String host = "";
        try {
            host = new URL(url).getHost();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            if (href.startsWith("./")) {
                href = href.replace("./", "/");
                String tempUrl = url.substring(0, url.lastIndexOf("/"));
                href = tempUrl + href;
            }
            if (href.startsWith("../")) {
                href = href.replace("../", "");
                href = "/" + href;
            }
            if (href.startsWith("/")) {
                href = host + href;
            }
            if (!href.startsWith("http")) {
                href = Regex.matchString(url, "http[s]{0,1}://") + href;
            }
        } catch (NullContentMatchedException e) {
            e.printStackTrace();
        }
        return href;
    }

    /**
     * 存储领导动态新闻
     *
     * @param entity   领导新闻实体
     * @param fullText 新闻全文,用以检索领导名字
     */
    public static void storeNews(LeaderNewsEntity entity, String fullText, String threadName) {

        String title = entity.getTitle();
        List<Integer> leaderIdList = new ArrayList<>();
        for (LeaderEntity leaderEntity : LEADER_ENTITY_LIST) {
            String name = leaderEntity.getName();
            if ((title + fullText).contains(name)) {
                leaderIdList.add(leaderEntity.getId());
            }
        }
        entity.setIdList(leaderIdList);
        if (!leaderIdList.isEmpty()) {
            OPERATOR.insertLeaderNews(entity);
            printlnInfo(threadName + " 插入领导动态:" + entity.getTitle());
        } else {
            printlnInfo(threadName + " 没有领导信息:" + entity.getUrl());
        }
    }
}
